<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain size="mini" @click="handleAdd({ type: 'substation' })"
          v-hasPermi="['maintenance:substation:add']">新增变电站
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" icon="el-icon-download" @click="handleExport" v-if="true"
          v-hasPermi="['maintenance:substation:export']">导出</el-button>
      </el-col>

      <el-form ref="queryDataRef" :inline="true" :model="queryData" class="el-form-search">
        <!--变电站名称-->
        <el-form-item class="el-form-search-item" label="名称" prop="substationName">
          <el-input v-model.trim="queryData.substationName" clearable placeholder="变电站名称"></el-input>
        </el-form-item>
        <!--地区-->
        <el-form-item class="el-form-search-item" label="地区" prop="areaNum">
          <treeselect v-model="queryData.areaNum" :normalizer="normalizer" :options="areaOptions" placeholder="选择地区"
            style="width: 180px" />
        </el-form-item>
        <!--客户公司名称-->
        <el-form-item class="el-form-search-item" label="客户" prop="customerNum">
          <el-select v-model="queryData.customerNum" clearable filterable placeholder="请选择客户">
            <el-option v-for="item in customerOptions" :key="item.num"
              :label="item.companyName + '-' + item.contactName" :value="item.num"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handelQuery">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table border :data="substationList" :height="tableHeight" border stripe>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :border="childBorder" :data="props.row.connectionPointList"
            :header-cell-style="{ background: '#dadde7', textSize: '14px' }" :highlight-current-row="false" stripe
            border v-if="props.row != null">
            <el-table-column width="20"></el-table-column>
            <el-table-column align="center" label="出线名称" prop="connectionPointName" width="110"></el-table-column>
            <el-table-column align="center" label="出线容量" prop="capacity" width="100"></el-table-column>
            <el-table-column align="center" label="电压等级" prop="voltageLevel" width="100"></el-table-column>
            <el-table-column align="center" label="电流变比" prop="currentRatio" width="100"></el-table-column>
            <el-table-column align="center" label="地区" prop="ancestorNames" width="300"></el-table-column>
            <el-table-column align="center" label="具体位置" prop="location" width="300"></el-table-column>
            <el-table-column align="center" label="联系人" prop="contactName"></el-table-column>
            <el-table-column align="center" label="联系方式" prop="phone"></el-table-column>
            <el-table-column align="center" label="经度" prop="lon" width="100"></el-table-column>
            <el-table-column align="center" label="维度" prop="lat" width="100"></el-table-column>

            <el-table-column align="center" label="操作" fixed="right" width="200">
              <template slot-scope="scope">
                <el-button icon="el-icon-edit" type="text" @click="
                  handleEdit({ type: 'connectionPoint', num: scope.row.num })
                  " v-hasPermi="['maintenance:connectionPoint:edit']">修改
                </el-button>
                <el-button icon="el-icon-delete" type="text" @click="
                  handleDelete({
                    type: 'connectionPoint',
                    num: scope.row.num,
                  })
                  " v-hasPermi="['maintenance:connectionPoint:remove']">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" label="#" type="index" width="50" :resizable="false">
        <template slot-scope="scope">
          <span>{{
            (queryData.pageNum - 1) * queryData.pageSize + scope.$index + 1
            }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="变电站名称" prop="substationName" width="200"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="地区" prop="ancestorNames" show-overflow-tooltip width="150"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="变电站类型" prop="type" show-overflow-tooltip width="150"
        :formatter="substationTypeFormatter"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="位置" show-overflow-tooltip prop="location"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="公司名称" show-overflow-tooltip prop="customer.companyName" width="120"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="联系人" prop="customer.contactName" width="100"
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="电话" prop="customer.phone" width="100" :resizable="false"></el-table-column>
      <el-table-column align="center" label="总容量" prop="totalCapacity" width="100" :resizable="false">
        <template slot-scope="scope">
          {{ scope.row.totalCapacity.toFixed(3) }}MW
        </template>
      </el-table-column>
      <el-table-column align="center" label="出线数量" prop="pointsAmount" width="85" :resizable="false"></el-table-column>
      <el-table-column align="center" label="规模描述" prop="scaleDesc" show-overflow-tooltip
        :resizable="false"></el-table-column>
      <el-table-column align="center" label="操作" width="200" :resizable="false">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-plus" @click="handleAdd({ type: 'connectionPoint', row: scope.row })"
            v-hasPermi="['maintenance:connectionPoint:add']">出线
          </el-button>
          <el-button icon="el-icon-edit" type="text" @click="handleEdit({ type: 'substation', num: scope.row.num })"
            v-hasPermi="['maintenance:substation:edit']">修改
          </el-button>
          <el-button icon="el-icon-delete" type="text" @click="handleDelete({ type: 'substation', num: scope.row.num })"
            v-hasPermi="['maintenance:substation:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryData.pageNum" :limit.sync="queryData.pageSize"
      @pagination="getList" />

    <!--变电站对话框-->
    <el-dialog :title="substationTitle" :visible.sync="substationOpen" :close-on-click-modal="false" v-dialogDrag
      width="800px">
      <el-form :model="substationFormData" :rules="substationRules" ref="substationFormDataRef" label-width="92px"
        label-position="left">
        <!--第一行-->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="名称" prop="substationName">
              <el-input v-model.trim="substationFormData.substationName" clearable placeholder="请输入变电站名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 下拉框 -->
            <el-form-item label="客户" prop="customerNum">
              <el-select v-model="substationFormData.customerNum" clearable filterable placeholder="请选择客户">
                <el-option v-for="item in customerOptions" :key="item.num"
                  :label="item.companyName + '-' + item.contactName" :value="item.num"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="地区" prop="areaNum">
              <treeselect v-model="substationFormData.areaNum" :normalizer="normalizer" :options="areaOptions"
                placeholder="选择地区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="substationFormData.type" clearable filterable placeholder="请选择选项">
                <el-option v-for="item in substationTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--textarea输入-->
            <el-form-item label="位置" prop="location">
              <el-input v-model.trim="substationFormData.location" :maxlength="150" :rows="2" clearable
                placeholder="请输入变电站所在位置" resize="none" show-word-limit type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第四行-->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="总容量" prop="totalCapacity">
              <el-input v-model.trim="substationFormData.totalCapacity" :disabled="disabled" clearable
                placeholder="请输入变电站总容量">
                <template slot="append">MW</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出线数量" prop="pointsAmount">
              <el-input v-model.trim="substationFormData.pointsAmount" :disabled="disabled" clearable
                placeholder="请输入变电站下出线数量"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--textarea输入-->
            <el-form-item label="规模描述" prop="scaleDesc">
              <el-input v-model.trim="substationFormData.scaleDesc" :maxlength="150" :rows="2" clearable
                placeholder="请输入变电站规模描述" resize="none" show-word-limit type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData">提交</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>

    <!-- 出线对话框 -->
    <el-dialog :title="connectionPointTitle" :visible.sync="connectionPointOpen" :close-on-click-modal="false"
      v-dialogDrag width="800px">
      <el-form ref="connectionPointFormDataRef" :model="connectionPointFormData" :rules="connectionPointRules"
        label-width="80px" label-position="left">
        <!-- 第一行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--出线名称-->
            <el-form-item label="名称" prop="connectionPointName">
              <el-input v-model.trim="connectionPointFormData.connectionPointName" clearable
                placeholder="出线名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行、第四行、第五行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--变电站-->
            <el-form-item label="变电站" prop="substationNum">
              <el-select v-model="connectionPointFormData.substationNum" clearable filterable placeholder="请选择变电站"
                class="from-select" disabled>
                <el-option v-for="item in substationList" :key="item.num" :label="item.substationName"
                  :value="item.num"></el-option>
              </el-select>
            </el-form-item>
            <!-- 地区 -->
            <el-form-item label="地区" prop="ancestorNames">
              <!-- <treeselect
                v-model="connectionPointFormData.area"
                :normalizer="normalizer"
                :options="areaOptions"
                placeholder="选择地区"
              /> -->
              <el-input v-model.trim="connectionPointFormData.ancestorNames" clearable placeholder="地区"
                disabled></el-input>
            </el-form-item>
            <!-- 位置 -->
            <el-form-item label="位置" prop="location">
              <el-input v-model.trim="connectionPointFormData.location" :maxlength="100" :rows="2" clearable
                placeholder="输入出线位置" resize="none" show-word-limit type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="容量" prop="capacity">
              <el-input v-model.trim="connectionPointFormData.capacity" clearable placeholder="出线容量">
                <template slot="append">MW</template>
              </el-input>
            </el-form-item>
            <el-form-item label="电压等级" prop="voltageLevel">
              <el-select v-model="connectionPointFormData.voltageLevel" placeholder="出线电压等级" class="from-select">
                <el-option v-for="dict in voltageLevelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictLabel"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="电流变比" prop="currentRatio">
              <el-input v-model.trim="connectionPointFormData.currentRatio" clearable placeholder="出线电流变比">
                <!-- <template slot="append">MW</template> -->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--联系人-->
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model.trim="connectionPointFormData.contactName" clearable placeholder="联系人名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--联系人-->
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model.trim="connectionPointFormData.phone" clearable placeholder="联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第六行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--经度-->
            <el-form-item label="经度" prop="lon">
              <el-input v-model.trim="connectionPointFormData.lon" clearable placeholder="经度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--维度-->
            <el-form-item label="维度" prop="lat">
              <el-input v-model.trim="connectionPointFormData.lat" clearable placeholder="维度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData">提交</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSubstationFold,
  getSubstationByNum,
  delSubstation,
  editSubstation,
  addSubstation,
} from "@/api/maintenance/substation";
import {
  getConnectionPointByNum,
  delConnectionPoint,
  editConnection,
  addConnectionPoint,
} from "@/api/maintenance/connectionPoint";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listArea } from "@/api/maintenance/area";
import { listCustomer } from "@/api/maintenance/customer";

export default {
  components: { Treeselect },
  data() {
    return {
      total: 0,

      /**
       * 查询数据
       */
      /**搜索栏数据 */
      queryData: {
        pageNum: 1,
        pageSize: 30,
        substationName: undefined,
        areaNum: undefined,
        customerNum: undefined,
        contactName: undefined,
        orderByColum: "update_time",
        isAsc: "asc",
      },

      /**
       * 表格数据
       */
      substationList: [],
      tableHeight: "calc(100vh - 200px)",
      childBorder: false,

      /**
       * 变电站对话框
       */
      substationFormData: {
        substationNum: undefined,
        substationName: undefined,
        type: undefined,
        totalCapacity: undefined,
        pointsAmount: undefined,
        location: undefined,
        contactName: undefined,
        phone: undefined,
        lon: undefined,
        lat: undefined,
      },

      substationRules: {
        substationName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        totalCapacity: [
          { validator: this.formValidation.validateNumber, trigger: "blur" },
          { required: true, message: "总容量不能为空", trigger: "blur" },
        ],
        pointsAmount: [
          { validator: this.formValidation.validateNumber, trigger: "blur" },
          { required: true, message: "出线数量不能为空", trigger: "blur" },
        ],
      },
      disabled: false,
      substationTitle: "",
      substationOpen: false,

      /**
       * 出线对话框
       */
      connectionPointFormData: {},
      connectionPointRules: {
        connectionPointName: [
          { required: true, message: "出线名称不能为空", trigger: "blur" },
        ],
        customerNum: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        substationNum: [
          {
            required: true,
            message: "变电站不能为空",
            trigger: "blur",
          },
        ],
        capacity: [
          { required: true, message: "容量不能为空", trigger: "blur" },
          {
            validator: this.formValidation.validateNumber,
            message: "只能输入整数或小数",
            trigger: "blur",
          },
        ],
        area: [{ required: true, message: "地区不能为空", trigger: "blur" }],
        lon: [
          {
            required: true,
            validator: this.formValidation.validatorLongitude,
            message: "经度范围：-180~180（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
        lat: [
          {
            required: true,
            validator: this.formValidation.validatorLatitude,
            message: "纬度范围：-90~90（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
      },
      connectionPointTitle: "",
      connectionPointOpen: false,
      /**
       * 操作类型参数
       */
      operationParam: {
        type: undefined,
        num: undefined,
      },
      // 地区下拉框
      areaOptions: [],
      substationTypeOptions: [],
      //客户下拉框
      customerOptions: [],
      //电压等级
      voltageLevelOptions: [],
    };
  },
  created() {
    this.getList();
    // 查询地区列表
    listArea().then((response) => {
      this.areaOptions = this.handleTree(
        response.data.filter((item) => item.num != 1),
        "num"
      );
    });
    /**查询客户 */
    listCustomer().then((response) => {
      this.customerOptions = response.rows;
    });
    this.getDicts("zk_voltage_level").then((response) => {
      this.voltageLevelOptions = response.data;
    });
    this.getDicts("substation_type").then((response) => {
      this.substationTypeOptions = response.data;
    });
  },
  methods: {
    getList() {
      listSubstationFold(this.queryData).then((res) => {
        this.substationList = res.rows;
        this.total = res.total;
          this.$refs.elTable.doLayout();
      });
    },
    substationTypeFormatter(row, column) {
      console.log(row.type);
      return this.substationTypeOptions.find((item) => item.dictValue === row.type)?.dictLabel || row.type;
    },

    // 新增变电站/出线
    handleAdd(operationParam) {
      if (operationParam.type === "substation") {
        this.substationFormData = {
          totalCapacity: 0,
          pointsAmount: 0,
        };
        this.operationParam = operationParam;

        this.resetForm("substationFormDataRef");
        this.substationTitle = "新增变电站";
        this.disabled = true;
        this.substationOpen = true;
      } else {
        this.connectionPointFormData = {
          substationNum: operationParam.row.num,
          lon: 0,
          lat: 0,
          capacity: 0,
          area: operationParam.row.areaNum,
          ancestorNames: operationParam.row.ancestorNames,
        };
        this.operationParam = operationParam;
        this.resetForm("connectionPointFormDataRef");
        this.connectionPointTitle = "新增出线";
        this.connectionPointOpen = true;
      }
    },
    // 编辑变电站/出线
    handleEdit(operationParam) {
      if (operationParam.type === "substation") {
        this.resetForm("substationFormDataRef");
        this.operationParam = operationParam;
        getSubstationByNum(operationParam.num).then((response) => {
          this.substationFormData = response.data;
        });
        this.substationTitle = "编辑变电站";
        this.substationOpen = true;
      } else {
        this.resetForm("connectionPointFormDataRef");
        this.operationParam = operationParam;
        getConnectionPointByNum(operationParam.num).then((response) => {
          this.connectionPointFormData = response.data;
        });
        this.connectionPointTitle = "修改出线";
        this.connectionPointOpen = true;
      }
    },
    // 删除变电站/出线
    handleDelete(operationParam) {
      if (operationParam.type === "substation") {
        this.$modal
          .confirm("确认删除变电站吗？")
          .then(function () {
            return delSubstation(operationParam.num);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => { });
      } else {
        this.$modal
          .confirm("确认删除变电站吗？")
          .then(function () {
            return delConnectionPoint(operationParam.num);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => { });
      }
    },

    submitFormData() {
      if (this.operationParam.type === "substation") {
        this.$refs["substationFormDataRef"].validate((valid) => {
          if (valid) {
            if (this.substationFormData.num !== undefined) {
              //修改
              editSubstation(this.substationFormData).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.getList();
                this.substationOpen = false;
              });
            } else {
              //新增
              addSubstation(this.substationFormData).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.getList();
                this.substationOpen = false;
              });
            }
          }
        });
      } else {
        this.$refs["connectionPointFormDataRef"].validate((valid) => {
          if (valid) {
            if (this.connectionPointFormData.num !== undefined) {
              // 修改
              editConnection(this.connectionPointFormData).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.getList();
                this.connectionPointOpen = false;
              });
            } else {
              // 新增
              addConnectionPoint(this.connectionPointFormData).then(
                (response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.getList();
                  this.connectionPointOpen = false;
                }
              );
            }
          }
        });
      }
    },
    close() {
      this.substationOpen = false;
      this.connectionPointOpen = false;

      this.resetForm("substationFormDataRef");
      this.resetForm("connectionPointFormDataRef");
    },
    /** 转换地区数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.num,
        label: node.name,
        children: node.children,
      };
    },
    /**搜索 */
    handelQuery() {
      this.queryData.pageNum = 1;
      this.getList();
    },
    /**重置搜索 */
    resetQuery() {
      this.resetForm("queryDataRef");
      this.handelQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "zk/substation/export", //后端接口
        {
          ...this.queryData, // 参数
        },
        `变电站信息_${new Date().getTime()}.xlsx` //导出的文件名称
      );
    },
  },
};
</script>

<style lang="scss" scoped></style>
